import React, { Component } from 'react';
import {
  AsyncStorage,
} from 'react-native';
import keysData from '../../../res/data/keys.json'
import langsData from '../../../res/data/langs.json'

export var FLAG_LANGUAGE = { flag_language: 'language_dao_language', flag_key: 'flag_language_key' };

const FAVORITE_KEY_PREFIX = "favorite_"
export default class LanguageDao {
  constructor(flag) {
    this.flag = FAVORITE_KEY_PREFIX + flag;
  }

  fetch() {
    return new Promise((resolve, reject) => {
      AsyncStorage.getItem(this.flag, (error, result) => {
        if (error) {
          reject(error);
          return;
        } else {
          // 如果数据不为空，返回
          if (result) {
            try {
              resolve(JSON.parse(result));
            } catch (e) {
              reject(e);
            }
          } else {
            // 如果数据为空就加载keys.json获取数据
            // 第一次如果是language则从langsData中获取，否则从keysData获取
            var data = this.flag === FLAG_LANGUAGE.flag_language ? langsData : keysData;
            // 保存数据
            this.save(data);
            resolve(data);
          }
        }
      })
    })
  }

  save(data) {
    // 保存数据
    AsyncStorage.setItem(this.flag, JSON.stringify(data));
  }
}